<?php

namespace app\services;

use plugin\admin\app\model\CoinSpeed;
use plugin\admin\app\model\ExchangeRate;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserTeam;

class ExchangeRateService
{
    public static function data()
    {
        $rates = ExchangeRate::where('date', '<=', date('Y-m-d'))->orderByDesc('date')->offset(0)->limit(7)->get()->toArray();

        $up = 0;
        $length = count($rates);
        if ($length > 1) {
            $up = bcdiv(bcsub($rates[0]['exchange_rate'], $rates[1]['exchange_rate'], 4), $rates[1]['exchange_rate'], 4) * 100;
        }

        $baseRates = CoinSpeed::all()->toArray();

        $totalRegisterUserCount = User::count();
        $totalIdentifyUserCount = User::where('is_identify', 1)->count();

        return [
            'register_user_count' => $totalRegisterUserCount,
            'identify_user_count' => $totalIdentifyUserCount,
            'sb_exchange_rate' => self::getTodayExchangeRate() * 1000,        //今日兑换汇率
            'sb_base_rates' => $baseRates,             //速率数据
            'sb_current_base_rate' => self::getBaseRate(), //当前速率
            'sd_price_trend' => $rates,   //币价格走势
            'sd_up' => $up,    //币相对昨日变化幅度
            'sd_today_price' => self::getTodayExchangeRate(),    //今日币价格
        ];
    }

    public static function getTodayExchangeRate()
    {
        $rate = ExchangeRate::where('date', date('Y-m-d'))->first();

        return $rate['exchange_rate'] ?? 0;
    }

    public static function getBaseRate()
    {
        $userCount = User::count();
        $res = CoinSpeed::where('people_count', '<=', $userCount)->orderByDesc('id')->first();

        return $res['coin'];
    }

    public static function getTeamRate()
    {
        $config = ConfigService::getByGroup('coin');

        $speed = $config['identify_coin_speed_up'] ?? 10;

        $teamInfo = UserTeam::where('user_id', get_user_id())->first();

        return bcmul(bcmul($teamInfo['identify_recommend_count'], $speed, 2), self::getBaseRate(), 2);
    }
}